#include "decoratorquestionnairemodel.h"
#include "sd.h"
#include "readertomodel.h"
#include "writertomodel.h"
#include <QFile>
#include <QStandardItemModel>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QDebug>

DecoratorQuestionnaireModel::DecoratorQuestionnaireModel(QObject *p ) :
	QObject(p), m(new QStandardItemModel(0, 2,this)), q(-1),
	r(new ReaderToModel(m, new QXmlStreamReader(), this)),
	w(new WriterFromModel(m, new QXmlStreamWriter(), this)){
	m->setHeaderData(0, Qt::Horizontal, trUtf8("Текст"));
	m->setHeaderData(1, Qt::Horizontal, trUtf8("Тип"));
}

void DecoratorQuestionnaireModel::addQuestion ( ){
	int n = m->rowCount();
	m->insertRow(n);
	sd(m, n, 0, trUtf8("Напишите текст вопроса"));
	sd(m, n, 1, Radio);
}

void DecoratorQuestionnaireModel::selectQuestion (int question){
	q = question;
}

void DecoratorQuestionnaireModel::addVariant ( ){
	if(q >= 0){ //Если выделен какой то вопрос.
		if(m->index(q, 1).data() == Radio || m->index(q, 1).data() == Check){ // И тип вопроса подходящий
			QModelIndex i = m->index(q, 0);
			int n = m->rowCount(i);
			m->insertRow(n, i);
			if(n == 0){
				m->insertColumn(0, i);
			}
			sd(m, n, 0, trUtf8("Укажите вариант ответа"), i);
		}
	}
}

void DecoratorQuestionnaireModel::save (const QString & fn){
	w->streamWriter()->setDevice(new QFile(fn, this));
	w->write();
}


QAbstractItemModel * DecoratorQuestionnaireModel::model() const{
	return m;
}

void DecoratorQuestionnaireModel::open(const QString & fn){
	r->streamReader()->setDevice(new QFile(fn, this));
	r->read();
}

